from urllib.parse import urlencode

from django.conf import settings
from django.contrib.auth.backends import ModelBackend

from apps.users.models import User
from meiduo_mall.settings.dev import logger
import re

# 封装 生成  激活链接 的 函数
def generate_verify_email_url(user):
    # http://www.meiduo.site:8000/emails/verification/?
    # token=eyJhbGciOiJIUzUxMiIsImlhdCI6MTU2NjE5ODk4Mywi
    # ZXhwIjoxNTY2MjAyNTgzfQ.eyJ1c2VyX2lkIjo2LCJlbWFpbC
    # I6ImxpdWNoZW5nZmVuZzY2NjZAMTYzLmNvbSJ9.okIKKAHjeskFild3EZeK3034N2r0vMb_tvUaVA7h4qPdfxmsDG4JvzXsTLl2_98Ln6rpWN4EmAdrdthZeG2DdQ
    host_url = settings.EMAIL_ACTIVE_URL
    data_dict = {
        'user_id':user.id,
        'email':user.email
    }
    # verify_url = host_url + "?token=" + urlencode(data_dict)
    # verify_url = host_url + "?" + urlencode(data_dict)
    #进行加密操作
    from utils.secret import SecretOauth
    dumps_params = SecretOauth().dumps(data_dict)
    verify_url = host_url + "?token=" + dumps_params
    return verify_url


def get_user_by_account(account):
    try:
        if re.match('^1[345789]\d{9}$', account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)

    except User.DoesNotExist:
        logger.error('用户对象不存在')
        return None
    else:
        return user

class UsernameMobileAuthBackend(ModelBackend):
    """自定义用户认证后端"""

    #手机号登陆时 重写authenticate
    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        重写认证方法，实现多账号登录
        :param request: 请求对象
        :param username: 用户名
        :param password: 密码
        :param kwargs: 其他参数
        :return: user
        """
        # 根据传入的username获取user对象。username可以是手机号也可以是账号


    ####需要判断是否是前台登陆还是后台登陆
        #前台登陆的话，直接用  后台登陆时 需要进行设置只有管理员才能进行登陆
        if request is None:
            #后台 jwt调用时为传递request对象
            try:    #查询指定用户名 同时要求是管理员用户
                user = User.objects.get(username = username,is_staff=True)
            except:
                return None
            else:
                if user.check_password(password):
                    return user
                else:
                    return None
        else:
            #前台调用时传递request对象，只有后台的request为空
            user = get_user_by_account(username)
            # 校验user是否存在并校验密码是否正确
            if user and user.check_password(password):
                return user
            else:
                return None

